#include "bsp_adc.h"

stc_adc_t ADC;

///< ADC 采样端口初始化
static void App_AdcPortInit(void)
{    
    ///< 开启GPIO外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);
    
    Gpio_SetAnalogMode(GpioPortA, GpioPin0);        //PA00 (AIN0)
    Gpio_SetAnalogMode(GpioPortA, GpioPin2);        //PA02 (AIN2)
    Gpio_SetAnalogMode(GpioPortA, GpioPin5);        //PA05 (AIN5)
}

///< ADC 模块初始化
static void App_AdcInit(void)
{
    stc_adc_cfg_t              stcAdcCfg;

    DDL_ZERO_STRUCT(stcAdcCfg);
    
    ///< 开启ADC/BGR外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralAdcBgr, TRUE); 
    
    Bgr_BgrEnable();        ///< 开启BGR
    
    ///< ADC 初始化配置
    stcAdcCfg.enAdcMode         = AdcScanMode;              ///<采样模式-扫描
    stcAdcCfg.enAdcClkDiv       = AdcMskClkDiv2;            ///<采样分频,最大24Mhz,见手册P289
    stcAdcCfg.enAdcSampCycleSel = AdcMskSampCycle8Clk;      ///<采样周期数-8
    stcAdcCfg.enAdcRefVolSel    = AdcMskRefVolSelAVDD;      ///<参考电压选择-VCC
    stcAdcCfg.enAdcOpBuf        = AdcMskBufDisable;         ///<OP BUF配置-关
    stcAdcCfg.enInRef           = AdcMskInRefDisable;       ///<内部参考电压使能-关
    stcAdcCfg.enAdcAlign        = AdcAlignRight;            ///<转换结果对齐方式-右
    Adc_Init(&stcAdcCfg);
}


///< ADC 顺序扫描 功能配置
static void App_AdcSQRCfg(void)
{
    stc_adc_sqr_cfg_t          stcAdcSqrCfg;
    
    DDL_ZERO_STRUCT(stcAdcSqrCfg);
        
    ///< 顺序扫描模式功能及通道配置
    ///< 注意：扫描模式下，当配置转换次数为n时，转换通道的配置范围必须为[SQRCH(0)MUX,SQRCH(n-1)MUX]
    stcAdcSqrCfg.bSqrDmaTrig = FALSE;
    stcAdcSqrCfg.enResultAcc = AdcResultAccEnable;
    stcAdcSqrCfg.u8SqrCnt    = 3;
    Adc_SqrModeCfg(&stcAdcSqrCfg);

    Adc_CfgSqrChannel(AdcSQRCH0MUX, AdcExInputCH0);
    Adc_CfgSqrChannel(AdcSQRCH1MUX, AdcExInputCH2);
    Adc_CfgSqrChannel(AdcSQRCH2MUX, AdcExInputCH5);   
    ///< ADC 中断使能
    Adc_EnableIrq();
    EnableNvic(ADC_DAC_IRQn, IrqLevel3, TRUE);   
    ///< 启动顺序扫描采样
    Adc_SQR_Start();
}    

 ///< ADC 中断服务程序
void Adc_IRQHandler(void)
{    
	static int i= 0;
	if(TRUE == Adc_GetIrqStatus(AdcMskIrqSqr))
    {
        Adc_ClrIrqStatus(AdcMskIrqSqr);      
        ADC.Restult0[i]   = Adc_GetSqrResult(AdcSQRCH0MUX);  //获取顺序扫描通道0
        ADC.Restult2[i]   = Adc_GetSqrResult(AdcSQRCH1MUX);  //获取顺序扫描通道1
        ADC.Restult5[i]   = Adc_GetSqrResult(AdcSQRCH2MUX);  //获取顺序扫描通道2        
        ADC.RestultAcc[i] = Adc_GetAccResult();   
		ADC.converted_OK = TRUE;	
		if((++i) >= ADC_LOOP_NUM)
		{
			i = 0;
		}
        Adc_SQR_Stop();
    }
}


void BSP_ADC_Init(void)
{
	///< ADC 采样端口初始化
    App_AdcPortInit();   
    ///< ADC 模块初始化
    App_AdcInit();   
    ///< ADC 顺序扫描 功能配置
    App_AdcSQRCfg();
}


///*在主循环中调用 Adc_SQR_Start(); 启动一次转换,均值滤波*/



